import Native from 'native'

export const appScheme = {
  alipay: 'alipays://',
  weixin: 'weixin://'
}

export const appPkgName = {
  alipay: 'com.eg.android.AlipayGphone',
  weixin: 'com.tencent.mm'
}

const goOthersApp = (scheme) => new Promise((resolve) => {
  if (Native.IS_ANDROID) {
    const packageName = appPkgName[scheme.slice(0, 6)]
    Native.checkInstalledApp({
      packageName
    }, res => {
      resolve()
      if (res.data.installed === 'Y') {
        window.location = scheme
      }
    })
    resolve()
  } else {
    Native.compareVersion('1.2.6', (result) => {
      if (result >= 0) {
        resolve()
        return Native.openURL(scheme, 'scheme')
      }
      const ifr = document.createElement('iframe')
      ifr.src = scheme
      ifr.style.display = 'none'
      document.body.appendChild(ifr)
      setTimeout(() => {
        resolve()
        window.location = scheme
      }, 500)
      setTimeout(() => (document.body.removeChild(ifr)), 1000)
    })
  }
})

export default goOthersApp
